package com.fjwt.gz.coupon.gtpay.demo;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;

import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

@Slf4j
public class MktSignUtil {
	/**
	 * 随机盐值
	 */
	private static final String CONSTANT = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

	/**
	 * 获取随机长度字符串(盐值)
	 * @param length
	 * @return
	 */
	public static String getStringNumRandom(int length){

		Random random = new Random();
		StringBuilder stringBuilder = new StringBuilder(length);

		for (int i=0;i<length;i++){
			stringBuilder.append(CONSTANT.charAt(random.nextInt(CONSTANT.length())));
		}
		return stringBuilder.toString();
	}
	public static String encrypt(String keySecret,String text){
		return Md5Crypt.md5Crypt(text.getBytes(),keySecret);
	}

	public static boolean checkSign(JSONObject reqJson,String secretKey,String sign){
		return sign.equals(createSign(reqJson,secretKey));
	}
    public static String createSign(JSONObject reqJson,String secretKey) {
		Map<String, String> businessInfoMap =JSONObject.parseObject(reqJson.toJSONString(), new TypeReference<Map<String, String>>(){});
		StringBuilder stringBuilder = new StringBuilder();
		Map<String,String> map = new TreeMap<String,String>(businessInfoMap);
		for(String key : map.keySet()){
			if("sign".equals(key)){
				continue;
			}
			stringBuilder.append(key).append("=").append(map.get(key)).append("&");
		}
		stringBuilder.toString().substring(0,stringBuilder.toString().length()-1);
		log.info("secretKey:{}",secretKey);
		log.info("toSign:{}",stringBuilder.substring(0, stringBuilder.lastIndexOf("&")).toString());
		log.info("sign:{}",MD5Utils.sign(secretKey, stringBuilder.substring(0, stringBuilder.lastIndexOf("&")).toString(), "UTF-8"));
		return MD5Utils.sign(secretKey, stringBuilder.substring(0, stringBuilder.lastIndexOf("&")).toString(), "UTF-8");
    }

}